import {createRouter,createWebHistory} from 'vue-router';
import Home from '@/views/Home.vue';
import {getLocal} from '@/utils';
//创建路由配置
const routes = [
    {
        path:'/',
        redirect:'/home'
    },
    {
        name:'home',
        path:'/home',
        component:Home
    },
    {
        name:'category',
        path:'/category',
        component:()=>import('@/views/Category.vue')
    },
    {
        name:'cart',
        path:'/cart',
        component:()=>import('@/views/Cart.vue'),
        meta:{needLogin:true}
    },
    {
        name:'user',
        path:'/user',
        component:()=>import('@/views/User.vue'),
        meta:{needLogin:true}
    },
    {
        name:'login',
        path:'/login',
        component:()=>import('@/views/Login.vue')
    },
    {
        name:'product',
        path:'/product/:id',
        component:()=>import('@/views/ProductDetail.vue')
    },
    {
        name:'product-list',
        path:'/product-list',
        component:()=>import('@/views/ProductList.vue')
    }
]
//可以创建路由的实例
const router = createRouter({
    history:createWebHistory(),
    routes
})
//在每次跳转新的路径的时候要进行判断
router.beforeEach(to=>{
    //获取上次用户登录之后保存的token
    let token= getLocal('token');
    //如果获取到了，说明用户已经登录了
    if(token){
        if(to.path === '/login'){
            return {
                path:'/',
                replace:true
            }
        }else{
            return true;
        }
    }
    //因为有可能是多级路由，所以matched是一个数组
    //只要数组中有任何一个route配置有meta.needLogin属性，就需要登录
    if(to.matched.some(item=>item.meta.needLogin)){
        //本来想访问to.path,但是因为未登录跳到登录页登录
        //等登录了以后还要跳回to.path继续访问
        return {
            path:'/login',
            query:{
                ...to.query,
                redirect:to.path
            }
        }
    }
});
export default router;